﻿using System.Net;
using System.Xml.Serialization;

namespace AsyncAwaitLesson01
{
    /// <summary>
    /// 这个demo是c#高级编程第11版第15章的AsyncHistory示例
    /// </summary>
    internal class Program
    {
        private const string url = "http://www.cninnovation.com";
        static async Task Main(string[] args)
        {
            //SynchronizedAPI();

            //AsynchronousPattern();

            //EventBasedAsyncPattern();

            await TaskBaseAsyncPatternAsync();
            Console.WriteLine("Hello, World!11111111111111111111");


            Console.ReadKey();
        }

        /// <summary>
        /// 同步调用
        /// </summary>
        static void SynchronizedAPI()
        {
            Console.WriteLine(nameof(SynchronizedAPI));
            using (var client = new WebClient())
            {
                string content = client.DownloadString(url);
                Console.WriteLine(content.Substring(0, 100));
            }

            Console.ReadLine();
        }

        /// <summary>
        /// 异步模式
        /// </summary>
        private static void AsynchronousPattern()
        {
            Console.WriteLine(nameof(AsynchronousPattern));
            WebRequest request = WebRequest.Create("https://www.baidu.com");
            IAsyncResult result = request.BeginGetResponse(ReadResponse, null);


            #region 本地函数
            void ReadResponse(IAsyncResult ar)
            {
                using (WebResponse response = request.EndGetResponse(ar))
                {
                    Stream stream = response.GetResponseStream();
                    var reader = new StreamReader(stream);
                    string content = reader.ReadToEnd();
                    Console.WriteLine(content.Substring(0, 100));

                }
            } 
            #endregion
        }

        /// <summary>
        /// 基于事件的异步模式
        /// </summary>
        private static void EventBasedAsyncPattern()
        {
            Console.WriteLine(nameof(EventBasedAsyncPattern));
            using (WebClient client = new WebClient())
            {
                client.DownloadStringCompleted += (sender, e) =>
                {                    
                    string content = e.Result.Substring(0, 100);
                    Console.WriteLine(content);
                };
                client.DownloadStringAsync(new Uri(url));

                Console.ReadLine();
            }
        }

        /// <summary>
        /// 基于任务的异步模式
        /// </summary>
        /// <returns></returns>
        private static async Task TaskBaseAsyncPatternAsync()
        {
            Console.WriteLine(nameof(TaskBaseAsyncPatternAsync));
            using (WebClient client = new WebClient())
            {
                string content = await client.DownloadStringTaskAsync(url);
                Console.WriteLine(content.Substring(0, 100));
                Console.ReadLine(); 
            }
        }
    }
}
